package main

import (
	"fmt"
	"os"
	"strconv"
)

/*
*
Determine whether an integer is a palindrome. Do this without extra space.

click to show spoilers.

Some hints:
Could negative integers be palindromes? (ie, -1)

If you are thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?

There is a more generic way of solving this problem.

输入一个整数，判断是不是回文数

思路:
正整数倒转后如果和原值相等，则是回文数	不过由reverseinterger知道，翻转后有溢出的可能，既然不能全翻转，那我们翻转一半怎么样？

1.x是负数 或 x最后一位是0且x不等于0 则x不是回文数
2.0是回文数
3.翻转后一半，如何准确翻转一半？前半段为x，后半段为y，初始y=0且x>y,循环x/=10,y=y*10+x%10直至x<=y,此时如果x==y或x==y/10则为回文数

https://leetcode-cn.com/problems/palindrome-number/solution/
*/
func isPalindrome(x int) bool {
	if x < 0 || (x%10 == 0 && x != 0) { // corner case: 最后一位为0且值非0的数字不是回文数
		return false
	}

	if x == 0 { // corner case: 值为0 的数字是回文数
		return true
	}

	// 翻转一半，前半段x后半段y，初始x>y，一直x/-=10,y=y*10+x%10直至x<=y,此时如果x==y或x==y/10则x是回文数
	y := 0
	for x > y {
		y = y*10 + x%10
		x = x / 10
	}

	return x == y || (x == y/10)
}

func isPalindrome2(x int) bool {
	str := strconv.Itoa(x)
	p, q := 0, len(str)-1
	for p < q {
		if str[p] != str[q] {
			return false
		}
		p++
		q--
	}
	return true
}

func main() {
	if len(os.Args) != 2 {
		fmt.Fprintln(os.Stderr, "提示: 缺少输入")
		os.Exit(1)
	}
	intput, _ := strconv.Atoi(os.Args[1])
	fmt.Println(isPalindrome(intput))
}
